//
//  NativeLocationChannel.m
//  kq_flutter_widgets
//
//  Created by wtb on 2023/4/10.
//

#import "NativeLocationChannel.h"
#import "KqMLocation.h"
#import "ReactiveObjC.h"

@implementation NativeLocationChannel

+(void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar{
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"flutter.keqiang.com/location" binaryMessenger:[registrar messenger]];
    NativeLocationChannel *scan = [[NativeLocationChannel alloc] init];
    [registrar addMethodCallDelegate:scan channel:channel];
}

-(void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if ([@"startLocation" isEqualToString:call.method]){
        [[KqMLocation sharedInstance] getLocation];
        __block BOOL isBlock = NO;
        [RACObserve([KqMLocation sharedInstance], strAdress) subscribeNext:^(id  _Nullable x) {
            if (x) {
                if (!isBlock && x) {
                    isBlock = YES;
                    NSMutableDictionary *loc = [NSMutableDictionary dictionary];
                    [loc setValue:x forKey:@"address"];
                    [loc setValue:[KqMLocation sharedInstance].longitude forKey:@"longitude"];
                    [loc setValue:[KqMLocation sharedInstance].latitude forKey:@"latitude"];
                    result(loc);
                    [[KqMLocation sharedInstance] stopLocation];
                }
            }
        }];
    }else if ([@"stopLocation" isEqualToString:call.method]){
        //停止定位
        [[KqMLocation sharedInstance] stopLocation];
    }else if ([@"closeLocation" isEqualToString:call.method]){
        //关闭定位，释放资源
        [[KqMLocation sharedInstance] stopLocation];
    }else if ([@"openSetLocationPermission" isEqualToString:call.method]){
        //打开设置定位权限界面
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        });
        result(nil);
    }else if([@"isPermanentDeniedLocationPermission" isEqualToString:call.method]){
        //判断权限
        result([NSNumber numberWithBool:![[KqMLocation sharedInstance] isOpenPermission]]);
    }
}

@end
